package com.offcn.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.offcn.oss.service.OssService;
import com.offcn.oss.utils.ConstantPropertiesUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;


@Service
public class OssServicerImpl implements OssService {

    @Resource
    private OSS ossClient;

    @Override
    public Map<String, String> uploadFile() {
        //获取地域节点
        String endpoint = ConstantPropertiesUtils.END_POIND;
        // AccessKey  ID
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;

        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        String host = "https://" + bucketName + "." + endpoint;
        String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = formatDate + "/";
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0,1048576000);
            policyConds.addConditionItem(MatchMode.StartWith,PolicyConditions.COND_KEY, dir);
            String postPolicy = ossClient.generatePostPolicy(expiration,policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            //封装accessid、签名等信息返回
            respMap.put("accessid", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return respMap;
    }
}
